package com.itheima.web;

import com.itheima.base.BaseServlet;
import com.itheima.pojo.User;
import com.itheima.service.loginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author MaQing
 * @create 2022-05-10 08:18
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {
   /* protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        if ("login".equals(method)){
            login(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/error/error.jsp");
        }

    }
*/
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+" : "+password);

        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        System.out.println("7777");
        System.out.println("888888");
        System.out.println("999999");
        System.out.println("99900000");

        //service

        loginService service = new loginService();
        User user = service.login(u);

        if (user == null){
            //没查到
            request.setAttribute("msg","用户名或密码错误吖，请重新输入");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {//登录成功啦
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            //获取之前的oldUrl
            String oldUrl = (String) session.getAttribute("oldUrl");
            if (oldUrl != null){
                //返回首页
                response.sendRedirect(request.getContextPath()+oldUrl);
            }else {
                //返回首页
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
        }
    }

    /*protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }*/
}